import { defineStore } from 'pinia'
import { store } from '../index'
import { publicRoutes, privateRoutes } from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import { hasPermission } from '@/utils/route'

// 专门处理权限路由的模块
export const usePermissionStore = defineStore({
  id: 'permission',
  state: () => {
    return {
      // 路由表：初始拥有静态路由表
      routes: publicRoutes
    }
  },
  persist: {
    enabled: true
  },
  actions: {
    /**
     * 增加路由
     */
    setRoutes(newRoutes: any) {
      // 永远在静态路由的基础上增加新路由
      this.routes = [...newRoutes, ...publicRoutes]
    },
    /**
     * 根据权限筛选路由
     */
    filterRoutes(routeList:Array<RouteRecordRaw>, menus: any[]) {
      const routes:any[] = []
      // 路由权限匹配
      routeList.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(menus, tmp)) {
          if (tmp.children) {
            tmp.children = this.filterRoutes(tmp.children, menus)
          }
          routes.push(tmp)
        }
      })
      
      // 最后添加 不匹配路由进入 404
      // routes.push({
      //   path: '/:catchAll(.*)',
      //   redirect: '/404'
      // })
      this.setRoutes(routes)
      return routes
    }
  }
})

export function usePermissionSotreExternal() {
  return usePermissionStore(store)
}